<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\logic\GoodsLogic;
use app\admin\model\Gcategory;
use app\BaseController;
use think\facade\Request;
use think\facade\View;

class Goods extends BaseController {
    //商品添加
    public function goodAdd(){
        //添加商品
        if (Request::isPost()){
            $post=Request::post();
            //单图上传
            list($status,$paths) =Upload::getImgPath('img');
            //当状态为false时抛异常报错
            if (!$status){$this->error($paths);}
            //多图上传
            list($status,$pathss) =Upload::getImgPath('banner');
            //当状态为false时抛异常报错
            if (!$status){$this->error($pathss);}
            $data=GoodsLogic::GoodsAdd($post,$paths,$pathss);
            $res=\app\admin\model\Goods::AddGoodsInfo($data);
            if ($res){
                $this->success('添加成功',url('goodList'));
            }else{
                $this->error('添加失败');
            }
        }else{
            //分类
            $fenlei=GoodsLogic::goodCate();
            View::assign('fenlei',$fenlei);
            //品牌
            $pin=\app\admin\model\Goods::goodsPin();
            View::assign('pin',$pin);
            return View::fetch();
        }
    }






    public function goodList()
    {
        //接值
        $param = Request::param();
        //拼装where条件
        //$where = self::setGoodsWhere($param);
        //拼装搜索器data
        $data = GoodsLogic::setSearchData($param);
        //设置留值数据
        GoodsLogic::setGoodsData($param);
        //设置排序
        $order = GoodsLogic::setGoodsOrder($param);
        //查询数据
        $list = \app\admin\model\Goods::getGoodsList($data,$order,$param);
        //关键字变色
        //$list = GoodsLogic::changeFontColor($list,$param);
        View::assign('list',$list);
        //品牌列表
        $brand = \think\facade\Db::name('brand')->field(true)->select();
        View::assign('brand',$brand);
        //分类查询
        $cate = Gcategory::getCateListArr();

        View::assign('cate',$cate);
        return View::fetch();
    }


        //商品修改
     public function goodEdit(){
        if (Request::isPost()){
            $post=Request::post();
           //接轮播图  包含老图和临时目录下的图
            //old_imgs 老图
            //new_imgs 新图
            //把临时目录文件转到正式目录文件
            list($old_image,$new_image)=GoodsLogic::getImgUrl('zs/');
//            $post['banner_image']=[];  $new_image=[];
//            if (isset($post['new_imgs'])){
//                foreach ($post['new_imgs'] as $v){
//                    //取文件后缀
//                    $s=explode('.',$v);
//                    //正式路径
//                    //目录
//                    $path_date='zs/'.date('Y/m/d/');
//                    //文件名+后缀
//                    $path_dir=$path_date.md5(microtime(true).rand(100000,999999)).'.'.end($s);
//                    $post['banner_image'][]=$path_dir;
//                    //拼移动路径用的data
//                    //临时路径与正式路径数组
//                    $new_image[]=['new'=>$path_dir, 'old'=>$v,];
//                }
//            }
//            if (isset($post['old_imgs'])){
//                $post['banner_image']=array_merge($post['old_imgs'],$post['banner_image']);
//            }
           //$post['banner_image']=implode(",",$post['banner_image']);
            //多图存入数据库
            $post['banner_image']=implode(",",$old_image);
            //ajax多图上传  当上传图片时将上传图片的路径存入数据库中,没有上传图片的话为空
//            if (isset($post['imgs'])){
//              $post['banner_image']=implode(',',$post['imgs']);
//            }else{
//                $post['banner_image']='';
//            }
            //单图上传
           list($status,$default_image) =Upload::getImgPath('default_image');


//            //当状态为true时并且传过来的路径不为空时修改图片
          if ($status && !empty($default_image)){
             list($path_date, $path_dir)=GoodsLogic::setImgUrl($default_image,'zs/');
//               //有图上传时
//               //取文件后缀
//               $s=explode('.',$default_image);
//               //正式路径
//               //目录
//               $path_date='zs/'.date('Y/m/d/');
//               //文件名+后缀
//               $path_dir=$path_date.md5(microtime(true).rand(100000,999999)).'.'.end($s);
//               //让存入数据库的路径为正式路
              $post['default_image']=$path_dir;
           }

            $get = Request::get();
            //$data=GoodsLogic::goodsEditLogic($post,$path);
            //使用save修改 先查询在修改，查出老图路径
            $obj=\app\admin\model\Goods::find($post['goods_id']);
            //老的图片路径
            $old=$obj->default_image;
            //多图的老图路径
            $old_img=$obj->banner_image;
            //修改图片
            $res=$obj->save($post);
            //$res=\app\admin\model\Goods::goodEditInfo($post,[]);
            if ($res){
                //移动临时目录下图片到正式目录
                //判断是否存在文件夹
               GoodsLogic::getImgDir($new_image,'zs/','./img/');
                   echo "<pre>";
                   print_r($post);
                   echo "</pre>";die;
//                $path_date='zs/'.date('Y/m/d/');
//                if (!is_dir('./img/'.$path_date)){
//                    //参数1:文件名  参数2:权限  参数3:是否建立子文件夹
//                    mkdir('./img/'.$path_date,0777,true);
//                }
//                //循环拼接的临时路径与正式路径数组
//                foreach ($new_image as $v){
//                    copy("./img/".$v['old'],"./img/".$v['new']);
//                    //删除临时目录文件
//                    unlink("./img/".$v['old']);
//                }
                //删除多图中的老图被替换图片路径
                //判断上传路径是否存在,不存在时为老图路径

                if (isset($post['old_imgs']) && !empty($old_img)){
                    //array_diff 参数1中的数据 参数2不存在会被取出  作差值
                    $arr=array_diff($old_img,$post['old_imgs']);
                }else{
                    $arr=$old_img;
                }
                        //判断被删除的文件是否为数组,是否为空
                    if (is_array($arr) && !empty($arr)){
                        //删除老图路径
                        foreach ($arr as $v){
                            if (!empty($v)){unlink('./img/'.$v);}
                        }
                    }

                    //当状态为true并且临时文件路径不为空时
                if ($status && !empty($default_image)){
                    GoodsLogic::setImgDir($default_image,$path_date,$path_dir,'./img/');
//                    //移动临时文件到正式目录
//                    if (!is_dir('./img/'.$path_date)){
//                        //参数1:文件名  参数2:权限  参数3:是否建立子文件夹
//                        mkdir('./img/'.$path_date,0777,true);
//                    }
//                    //将临时目录文件复制到正式文件中
//                    copy('./img/'.$default_image,'./img/'.$path_dir);
//                    unlink('./img/'.$default_image);
                }
                //更换图片时删除之前文件中的路径
                if ($status && !empty($default_image) &&!empty($old)){unlink('./img/'.$old);}
                if ($post['btn']==1){
                    unset($get['goods_id']);
                    $this->success('修改成功',url('goodList',$get));
                }elseif ($post['btn']==0){
                    $this->success('修改成功',url('goodEdit',$get));
                }
            }else{
                $this->error('修改失败');
            }
        }else{
            //渲染页面
            $get=Request::get();
            $goods_info = \app\admin\model\Goods::goodEditInfo([],$get);
            View::assign($goods_info->toArray());
            //品牌循环展示
            $brand =\app\admin\model\Goods::goodsPin();
            View::assign('brandList',$brand);
            //分类循环展示
            $arr = GoodsLogic::goodCate();
            View::assign('cateList',$arr);
            return View::fetch();

        }


      }


    public function AgoodList(){
        //拼接where条件
        $where=self::setWhere();
        //保留值
        $data=self::setData();
        View::assign($data);
        $list=\app\admin\model\Goods::setGoodList($where);
        View::assign('list',$list);
        return View::fetch();
    }
      public static function setData(){
          $param=Request::param();
          $data=[
              'keywords'=>isset($param['keywords'])?$param['keywords']:'',
              'if_show'=>isset($param['if_show'])?$param['if_show']:[],
              'recommended'=>isset($param['recommended'])?$param['recommended']:''
          ];
          return $data;

          }
     public static function  setWhere(){
             $param=Request::param();
             $where=[];
             //模糊查询
             if (isset($param['keywords'] )&& !empty($param['keywords'])){
                 $where[]=['goods_name','like','%'.$param['keywords'].'%'];
             }
             //复选框查询
           if (isset($param['if_show']) && count($param['if_show'])==1){
             $where[]=['if_show','=',$param['if_show'][0]];
           }
           //单选
         if (isset($param['recommended']) && $param['recommended'] <>''){
             $where[]=['recommended','=',$param['recommended']];
         }





             return $where;
         }
    public function Acate(){

        //where条件
        $where=self::cateWhere();
        //sql语句
        $cate=Gcategory::cateList($where);
        //查询是否有下一级
        $cate=self::cateNext($cate);
        View::assign('cate',$cate);
        return View::fetch();
    }
    //看有没有下一个
     public static function AcateNext($cate){
         $param=Request::param();
         //查到parent_id所有的值
         $parent_all=Gcategory::cateListNext();
         $parent_all=array_unique($parent_all);
         foreach ($cate as &$v){
             if (in_array($v['cate_id'],$parent_all)){
               $v['next_cate']=1;
             }
         }
            return $cate;
         }
    //where拼接
     public static function   AcateWhere(){
           //接值
           $param=Request::param();
           //判断是否传值 默认为0
           $parent_id=isset($param['parent_id'])?$param['parent_id']:0;
           $where=[];
           $where[]=['parent_id','=',$parent_id];
          return $where;

         }

    public  function cate(){
        //where 拼接
        $where=self::cateWhere();
        $cate=Gcategory::cateList($where);
        //有没有下一级
        $cate=self::cateNext($cate);
        View::assign('cate',$cate);
         return View::fetch();

    }
     //连接where语句
     public static function  cateWhere(){
           $param=Request::param();
           $parent_id=isset($param['parent_id'])?$param['parent_id']:0;
           $where[]=['parent_id','=',$parent_id];
             return $where;
         }
       public static function cateNext($cate){
           $param=Request::param();
           //查parent_id个数
           $parent_id=Gcategory::cateListNext();
           foreach ($cate as &$v){
               if (in_array($v['cate_id'],$parent_id)){
                   $v['next_cate']=1;
               }
           }
            return $cate;
        }

    public function cateedit(){
        return View::fetch();
    }

    public function index(){
        $list=\app\admin\model\Goods::getGoodsList();
        echo "<pre>";
        print_r(  $list->toArray());
        echo "</pre>";

        View::assign('list',$list);
         return View::fetch();
     }



}
